package com.example.booksmanagementsystem.service;

import com.example.booksmanagementsystem.entity.Book;
import com.example.booksmanagementsystem.mapper.BookMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BookService {

    private final BookMapper bookMapper;

    // 使用构造器注入（避免字段注入）
    public BookService(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    // 查询方法
    public List<Book> getAllBooks() {
        return bookMapper.getAllBooks();
    }

    public int getBookCount() {
        return bookMapper.getNums();
    }

    public List<Book> getBooksByPage(int offset, int limit) {
        return bookMapper.getBooksByPage(offset, limit);
    }

    public Book getBookById(int id) {
        return bookMapper.getBookById(id);
    }

    public List<Book> searchBooksByName(String name) {
        return bookMapper.getBooksByName(name);
    }

    // 写操作添加事务
    @Transactional
    public void addBook(Book book) {
        validateBook(book);
        bookMapper.addBook(book);
    }

    @Transactional
    public void deleteBook(int id) {
        if (bookMapper.getBookById(id) == null) {
            throw new IllegalArgumentException("图书不存在");
        }
        bookMapper.deleteBook(id);
    }

    @Transactional
    public void updateBook(Book book) {
        validateBook(book);
        if (bookMapper.getBookById(book.getId()) == null) {
            throw new IllegalArgumentException("图书不存在");
        }
        bookMapper.updateBook(book);
    }

    private void validateBook(Book book) {
        if (book.getName() == null || book.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("图书名称不能为空");
        }
    }
}